package com.manger.common.tcp.server.handle;

import com.manger.common.tcp.constant.TcpDataType;
import com.manger.common.tcp.decode.impl.BusinessDecode;
import com.manger.common.tcp.encode.impl.ReceiptEncode;
import com.manger.common.tcp.server.TcpServer;
import com.manger.common.utils.SocketByteConvertUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.sf.json.JSONObject;

public class TcpServerHandler extends SimpleChannelInboundHandler<byte[]> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx,  byte[] bytes) throws Exception {
        try{
            byte b  = bytes[2];
            int type = SocketByteConvertUtils.bigEndian1ByteToInt(b);
            TcpDataType tcpDataType = TcpDataType.getTcpDataType(type);
            if(tcpDataType == TcpDataType.HEARTBEAT){
                System.out.println("接收心跳数据！");
                return;
            }
            int start = SocketByteConvertUtils.bigEndian2ByteToInt(SocketByteConvertUtils.midByteArray(bytes,0,2));
            System.out.println("type>>>>" + TcpDataType.getTcpDataType(type).getDesc() + ">>>>" + type);
            BusinessDecode businessDecode = new BusinessDecode(type);
            businessDecode.decode(bytes);
            JSONObject jsonObject = JSONObject.fromObject(businessDecode.getContent());
            System.out.println(businessDecode.getContent());
            JSONObject result = new JSONObject();
            result.put("serialNumber", jsonObject.getString("serialNumber"));
            result.put("sate", "1");
            result.put("reason", "success");
            ReceiptEncode receiptEncode = new ReceiptEncode();
            ctx.channel().writeAndFlush(receiptEncode.encode(result.toString()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("=======server===channelRegistered==================");
        super.channelActive(ctx);
        TcpServer.getInstance().setClientChannel(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        TcpServer.getInstance().setClientChannel(null);
    }

}
